const fs = require('fs');
const path = require('path');
const htmlparser2 = require('htmlparser2');

// 递归查找所有 .vue 文件
function findVueFiles(dir, fileList = []) {
  const files = fs.readdirSync(dir);
  files.forEach(file => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    if (stat.isDirectory()) {
      findVueFiles(filePath, fileList);
    } else if (filePath.endsWith('.vue')) {
      fileList.push(filePath);
    }
  });
  return fileList;
}

// 处理每个 .vue 文件，提取 <template> 部分的类名和 ID
function processVueFile(filePath) {
  const content = fs.readFileSync(filePath, 'utf-8');
  const handler = new htmlparser2.DomHandler((error, dom) => {
    if (error) {
      console.error(`Error parsing ${filePath}:`, error);
      return;
    }

    const templateTags = dom.filter(element => element.type === 'tag' && element.name === 'template');
    templateTags.forEach(templateTag => {
      const selectors = [];
      collectSelectors(templateTag, selectors);
      
      // 将 selectors 中的类名和 ID 写入对应的 CSS 文件
      const cssFilePath = filePath.replace('.vue', '.css');
      const cssContent = selectors.map(selector => `${selector} {}`).join('\n');

      // 检查是否存在同名 .css 文件
      if (!fs.existsSync(cssFilePath)) {
        fs.writeFileSync(cssFilePath, cssContent, 'utf-8');
        console.log(`Generated ${cssFilePath}`);
      } else {
        console.log(`${cssFilePath} already exists, skipping.`);
      }
    });
  });

  const parser = new htmlparser2.Parser(handler, { recognizeSelfClosing: true });
  parser.write(content);
  parser.end();
}

// 递归收集所有 <template> 下的类名和 ID
function collectSelectors(element, selectors) {
  if (element.children) {
    element.children.forEach(child => {
      if (child.attribs) {
        if (child.attribs.class) {
          const classes = child.attribs.class.split(/\s+/);
          classes.forEach(selector => {
            if (selector.trim() !== '') {
              selectors.push(`.${selector}`); // 类名选择器
            }
          });
        }
        if (child.attribs.id) {
          selectors.push(`#${child.attribs.id}`); // ID 选择器
        }
      }
      collectSelectors(child, selectors);
    });
  }
}

function generateCSSFiles(dir) {
  const vueFiles = findVueFiles(dir);
  vueFiles.forEach(processVueFile);
  console.log('CSS generation complete.');
}

module.exports = {
  generateCSSFiles
};
